# -*-coding:utf-8 -*-
import base64
import datetime
import os
import pathlib
import time

from .base import XZBaseHandler


class VideoHandler(XZBaseHandler):

    def add_history_video(self, data):
        # {'vehicleId': '80000001167', 'historyVideoName': 'B1562666578363.mp4'}
        terminal_id = self.map2new_terminal_id(data['vehicleId'])
        if not terminal_id:  # 找不到terminal_id
            return
        historyVideoName = data['historyVideoName']
        start_time = datetime.datetime.fromtimestamp(int(historyVideoName[1:-4])/1000).strftime('%Y-%m-%d %H:%M:%S')
        res = self.yb_api.add_history_video({
            'terminal_id': terminal_id,
            'terminal': terminal_id,
            'category': 2,       # 视频
            'encoding_type': 5,  # MP4
            'event_code': 8,     # 其它
            'channel_id': 1,
            'uri': data['historyVideoName'],
            'start_time': start_time,
            'end_time': start_time
        })

    def add_batch_history_video(self, data):
        # {'vehicleId': '80000001167', 'historyVideoName': 'B1562666578363.mp4'}
        pass

    def del_history_video(self, data):
        # {'vehicleId': '80000001167', 'historyVideoName': 'B1562666578363.mp4'}
        # self.logger.info(data)
        pass

    def video_upload(self, files, data):
        # #  * 报警事件视频上传
        vehicle_id = self.map2new_vehicle_id(data['vehicleId'][0])
        if not vehicle_id:  # 找不到vehicle_id
            return
        res = self.yb_api.send_alarm({
            "category": self.WARNING_TYPE_MAP[data['warningId'][0]],
            "start_time": data['warningTime'][0],
            "end_time": data['warningTime'][0],
            'vehicle_id': vehicle_id,
            'media_uri_category': 2,
            "media_uri": self.save(files),
            "location": {
                "latitude": data['gpsLat'][0],
                "longitude": data['gpsLon'][0],
                "gps_time": data['warningTime'][0]
            }
        }).json()
        return res

    def save(self, files):
        video_name = files["file"][0].name
        day = datetime.date.today().strftime('%Y%m%d')
        p = os.path.join(self.MEDIA_UPLOADS_PATH, f'{day}/videos/')
        pathlib.Path(p).mkdir(parents=True, exist_ok=True)
        with open(f'{p}/{video_name}', 'wb') as wf:
            wf.write(files["file"][0].body)
        return f'uploads/{day}/videos/{video_name}'
